package framework.transport.loadbalance;

import framework.registry.ServiceAddress;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Random;

@Slf4j
public class RandomLoadBalance implements LoadBalance{

    private final Random random;
    public RandomLoadBalance() {
        this.random = new Random();
    }

    @Override
    public ServiceAddress select(List<ServiceAddress> serviceAddresses) {
        if (serviceAddresses == null || serviceAddresses.isEmpty()) {
            throw new IllegalArgumentException("Empty service address list");
        }
        int index = random.nextInt(serviceAddresses.size());
        ServiceAddress serviceAddress = serviceAddresses.get(index);
        log.debug("select {}", serviceAddress.toJson());
        return serviceAddress;
    }
}
